package com.zcl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zcl.mapper.ClassesMapper;
import com.zcl.mapper.StudentMapper;
import com.zcl.pojo.PageResult;
import com.zcl.pojo.classes;
import com.zcl.pojo.student;
import com.zcl.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
//放入spring容器,与xml文件关联
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;
    //查询所有学生
    @Override
    public List<student> findAll() {
        //查询所有学生
         List<student> students = studentMapper.findAll();
         //设置每个学生的班级名字
        for (student student : students) {
//            根据不同学生的cid调用findbyid方法找到全部的班级名称并设置班级名称
            student.setCname(classesMapper.findById(student.getCid()).getCname());
        }
        return students;
    }

    @Override
    public PageResult<student> findByPage(int page, int pageSize) {
//        分页查询,开始分页
        PageHelper.startPage(page, pageSize);
        //获取所有学生
        List<student> students = findAll();
        System.out.println(students);
        //对象类型转化
        Page<student> studentPage= (Page<student>) students;
        //返回总数据和每页的结果集
        return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
    }


    @Override
    public PageResult<student> search(int page, int pageSize, student student) {
        //开始分页
        PageHelper.startPage(page,pageSize);
        //根据封装的要查找的属性的对象,根据条件查找
        List<student> students=this.findByWord(student);
        //类型转化成分页类型
        Page<student> studentPage= (Page<student>) students;
        //返回查询结果
        return new PageResult<>(studentPage.getTotal(),studentPage.getResult());

    }

    @Override
    public void insert(student student) {
        //添加学生
        studentMapper.insert(student);
    }

    @Override
    public void update(student student) {
        //修改学生
        studentMapper.update(student);
    }

    @Override
    public void delete(List<String> list) {
        //删除学生
        studentMapper.delete(list);
    }

    private List<student> findByWord(student student) {
        //根据条件对象,mapper调用方法查询学生
        List<student> students =studentMapper.findByWord(student);
        //遍历学生列表
        for (student st : students) {
            //设置班级名称
             Integer cid = st.getCid();
             classes classes = classesMapper.findById(cid);
             st.setCname(classes.getCname());
        }
        return students;
        }
}
